package com.hfuu.demo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hfuu.demo.domain.entity.User;
import com.hfuu.demo.domain.model.LoginUser;
import com.hfuu.demo.service.LoginService;
import com.hfuu.demo.utils.JwtUtil;
import com.hfuu.demo.utils.RedisCache;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @description:
 * @author: gunala
 * @date: 2024/2/4 15:32
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    private final RedisCache redisCache;

    @Override
    public Map<String, Object> login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (ObjectUtils.isNull(authenticate)){
            throw new  RuntimeException("登陆失败");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String, Object> map = Map.of("token", jwt);
        redisCache.setCacheObject("login:"+userId,loginUser);
        return map;
    }

    @Override
    public void logout() {
        //删除SecurityContextHolder中的userId
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        //authentication一定不为空，若为空，在Security过滤器链中会被拦截下来
        LoginUser logUser =(LoginUser) authentication.getPrincipal();
        String id = logUser.getUser().getId().toString();
        redisCache.deleteObject("login:"+id);
    }
}
